package cn.itrigger.dynamic.sql.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Stream;

/**
 * @author admin
 * @date 2018/9/21
 **/
public class FragmentCollector {
    List<String> fragments = new ArrayList<>();
    Map<String, Object> parameters = new HashMap<>();

    FragmentCollector() {
        super();
    }

    private FragmentCollector(FragmentAndParameters initialFragment) {
        add(initialFragment);
    }

    public void add(FragmentAndParameters fragmentAndParameters) {
        fragments.add(fragmentAndParameters.getFragment());
        parameters.putAll(fragmentAndParameters.getParameters());
    }

    public FragmentCollector merge(FragmentCollector other) {
        fragments.addAll(other.fragments);
        parameters.putAll(other.parameters);
        return this;
    }

    public Stream<String> fragments() {
        return fragments.stream();
    }

    public Map<String, Object> parameters() {
        return parameters;
    }

    public boolean hasMultipleFragments() {
        return fragments.size() > 1;
    }

    public static Collector<FragmentAndParameters, FragmentCollector, FragmentCollector> collect() {
        return Collector.of(FragmentCollector::new,
                FragmentCollector::add,
                FragmentCollector::merge);
    }

    public static Collector<FragmentAndParameters, FragmentCollector, FragmentCollector> collect(FragmentAndParameters initialFragment) {
        return Collector.of(() -> new FragmentCollector(initialFragment),
                FragmentCollector::add,
                FragmentCollector::merge);
    }
}
